package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	"strings"
)

type AddAdminUser struct {
	Id           string `json:"id"`
	Role         int64  `json:"role"`
	Name         string `json:"name"`
	Avatar       string `json:"avatar"`
	Account      string `json:"account"`
	Password     string `json:"password"`
	Desc         string `json:"introduction"`
	UniversityId string `json:"universityId"`
}

type AdminListParam struct {
	Name    string `json:"name"`
	PerPage int    `json:"perPage"`
	CurPage int    `json:"curPage"`
}

type AdminUser struct {
	Ctx iris.Context
}

func (c *AdminUser) OptionsCreate() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUser) PostCreate() interface{} {
	addAdminUser := AddAdminUser{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &addAdminUser)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(addAdminUser.Account) <= 0 {
		return utils.CommonRes(1000, "请输入管理员登录账号", "")
	}
	if len(addAdminUser.Password) < 6 {
		return utils.CommonRes(1000, "管理员密码至少6位", "")
	}
	if len(addAdminUser.Name) <= 0 {
		return utils.CommonRes(1000, "请输入管理员姓名", "")
	}
	if addAdminUser.Role <= 0 {
		return utils.CommonRes(1000, "请选择管理员角色", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	admin := new(models.Admin)
	admin.Name = addAdminUser.Name
	admin.RoleId = addAdminUser.Role
	admin.Avatar = addAdminUser.Avatar
	admin.Account = addAdminUser.Account
	admin.Password = utils.PasswordEncode(addAdminUser.Password)
	admin.Desc = addAdminUser.Desc
	admin.UniversityId = utils.Atoi64(addAdminUser.UniversityId)

	_, err = db.InsertOne(admin)

	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败:%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *AdminUser) OptionsInfo() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUser) GetInfo() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	session := sessions.Get(c.Ctx)
	adminUserId := session.Get("adminUserId")
	admin := new(models.Admin)
	ok, err := db.ID(adminUserId).Get(admin)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("管理员信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "管理员信息获取失败", admin)
	}

	role := new(models.Role)
	ok, err = db.Id(admin.RoleId).Get(role)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取管理员角色信息失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "获取管理员角色信息失败", admin)
	}

	admin.Roles = strings.Split(role.Authorities, ",")

	return utils.CommonRes(20000, "信息获取成功", admin)
}

func (c *AdminUser) OptionsDetail() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUser) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "参数不完整", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	admin := new(models.Admin)
	ok, err := db.ID(editParam.Id).Get(admin)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}

	return utils.CommonRes(20000, "信息获取成功", admin)
}

func (c *AdminUser) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUser) PostList() interface{} {
	adminListParam := AdminListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &adminListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	start := (adminListParam.CurPage - 1) * adminListParam.PerPage
	adminList := make([]models.Admin, 0)
	sess := db.Limit(adminListParam.PerPage, start)
	if len(adminListParam.Name) > 0 {
		sess = sess.Where("name like ?", fmt.Sprintf("%%%s%%", adminListParam.Name))
	}
	err = sess.Find(&adminList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取管理员列表:%s", err.Error()), "")
	}

	countSess := db.Where("id > ?", 0)
	if len(adminListParam.Name) > 0 {
		countSess = countSess.Where("name like ?", fmt.Sprintf("%%%s%%", adminListParam.Name))
	}
	total, err := countSess.Count(new(models.Admin))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取管理员列表:%s", err.Error()), "")
	}

	for i, item := range adminList {
		adminList[i].CreatedTime = item.Created.Format("2006-01-02 15:04")
	}

	data := map[string]interface{}{
		"total": total,
		"list":  adminList,
	}

	return utils.CommonRes(20000, "成功获取管理员列表", data)
}

func (c *AdminUser) OptionsEdit() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUser) PostEdit() interface{} {
	addAdminUser := AddAdminUser{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &addAdminUser)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(addAdminUser.Id) <= 0 {
		return utils.CommonRes(1000, "请提供管理员id", "")
	}
	if len(addAdminUser.Account) <= 0 {
		return utils.CommonRes(1000, "请输入管理员登录账号", "")
	}
	if len(addAdminUser.Password) > 0 && len(addAdminUser.Password) < 6 {
		return utils.CommonRes(1000, "管理员密码至少6位", "")
	}
	if len(addAdminUser.Name) <= 0 {
		return utils.CommonRes(1000, "请输入管理员姓名", "")
	}
	if addAdminUser.Role <= 0 {
		return utils.CommonRes(1000, "请选择管理员角色", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	updateData := map[string]interface{}{
		"role_id":       addAdminUser.Role,
		"account":       addAdminUser.Account,
		"name":          addAdminUser.Name,
		"avatar":        addAdminUser.Avatar,
		"desc":          addAdminUser.Desc,
		"university_id": addAdminUser.UniversityId,
	}
	if len(addAdminUser.Password) > 0 {
		updateData["password"] = utils.PasswordEncode(addAdminUser.Password)
	}

	_, err = db.Table(new(models.Admin)).ID(addAdminUser.Id).Update(updateData)
	if err != nil {
		return utils.CommonRes(1000, "操作失败", "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *AdminUser) OptionsDel() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUser) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "请提供要删除项的id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		admin := new(models.Admin)
		db.ID(id).Get(admin)
		db.ID(id).Delete(admin)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
